<template>
  <div>
    <el-card class="login-form-layout">
      <el-form autoComplete="on"
               :model="loginForm"
               :rules="loginRules"
               ref="loginForm"
               label-position="left">
        <div style="text-align: center">
          <svg-icon icon-class="login-mall" style="width: 56px;height: 56px;color: #409EFF"></svg-icon>
        </div>
        <h2 class="login-title color-main">会学助手</h2>
        <el-form-item prop="username">
          <el-input name="username"
                    type="text"
                    v-model="loginForm.username"
                    autoComplete="on"
                    placeholder="请输入用户名">
          <span slot="prefix">
            <svg-icon icon-class="user" class="color-main"></svg-icon>
          </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password"
                    :type="pwdType"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.password"
                    autoComplete="on"
                    placeholder="请输入密码">
          <span slot="prefix">
            <svg-icon icon-class="password" class="color-main"></svg-icon>
          </span>
            <span slot="suffix" @click="showPwd">
            <svg-icon icon-class="eye" class="color-main"></svg-icon>
          </span>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 60px;text-align: center">
          <el-button style="width: 45%" type="primary" :loading="loading" @click.native.prevent="handleLogin">
            登录
          </el-button>
          <el-button style="width: 45%" type="primary" @click.native.prevent="showRegDialog()">
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog title="注册" :visible.sync="regFormVisible">
   
    <el-form :model="regForm" ref="regFormRef" :rules="regFormRule" size="mini" inline>
        <el-form-item label="用 户 名 : " ref="usernameRef" name="username" prop="username" size="mini">
          <el-input v-model="regForm.username" autocomplete="off" @blur="check()"></el-input>
        </el-form-item>
         <el-form-item label="密   码     :"  prop="password" size="mini">
        <el-input   :type="pwdType"
                   
                    v-model="regForm.password"
                  
                    placeholder="请输入密码"> </el-input>
        </el-form-item>
        <el-form-item label="密码确认:" prop="password2" size="mini">
        <el-input   size="mini"
                    :type="pwdType"
                    v-model="regForm.password2"
                   
                    placeholder="请再次输入密码"></el-input>
        </el-form-item>


        <el-form-item label="真实姓名"  prop="realname"  size="mini" >
            <el-input v-model="regForm.realname" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="电话"   size="mini" prop="telphone">
            <el-input v-model="regForm.telphone" autocomplete="off"></el-input>
       </el-form-item>

        <el-form-item label="角色"   size="mini" prop="rolenames">
           <el-select v-model="regForm.roleid"  placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>


      
      <el-form-item label="备注" label-width="`120px`" >
        <el-input v-model="regForm.comment" autocomplete="off"></el-input>
      </el-form-item>

     
          
      
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="regFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleRegister('regFormRef')">确 定</el-button>
    </div>
  </el-dialog>


    <img :src="login_center_bg" class="login-center-layout">
   
  </div>
</template>

<script>
  import {isvalidUsername} from '@/utils/validate';
  import {setSupport,getSupport,setCookie,getCookie} from '@/utils/support';
  import {checkUsername,register} from '@/api/login';
  import {fetchListAll as fetchRoleListAll} from '@/api/role';
  

  import login_center_bg from '@/assets/images/login_center_bg.png'

  export default {
    name: 'login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.length < 3) {
          callback(new Error('密码不能小于3位'))
        } else {
          callback()
        }
      };
      const validateTelphone = (rule, value, callback) => {
        if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
      };

      return {
        loginForm: {
          username: 'luyuan',
          password: 'luyuan',
        },


        loginRules: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePass}]
        },
        loading: false,
        pwdType: 'password',
        login_center_bg,
        
        regForm: {
          username: '',
          password: '',
          password2: '',
          realname:'',
         
          roleid:null,
          comment: '',
        },
        regFormRule: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePass}],
          password2: [{required: true, trigger: 'blur', validator: validatePass}],
          telphone: [{required: true, trigger: 'blur', validator: validateTelphone}],
          realname: [{required: true, trigger: 'blur'}],
          roleid: [{required: true, trigger: 'blur'}],
          birthday: [{required: true, trigger: 'blur'}],
        },
        regFormVisible:false,

        roleOptions:[],
      }
    },
    created() {
      this.loginForm.username = getCookie("username");
      this.loginForm.password = getCookie("password");
      if(this.loginForm.username === undefined||this.loginForm.username==null||this.loginForm.username===''){
        this.loginForm.username = 'admin';
      }
      if(this.loginForm.password === undefined||this.loginForm.password==null){
        this.loginForm.password = '';
      }



      fetchRoleListAll().then(response=>{
        
          let roleList = response.data.list;

          for (let i = 0; i < roleList.length; i++) {
                this.roleOptions.push({label: roleList[i].Rolename, value: roleList[i].Id});
          }
          
                  
        }).catch((error) => {
                console.log(error)
              
        });

    },
    methods: {
      showRegDialog(){
        
        this.regForm.username=''
        this.regForm.password=''
        this.regForm.password2=''
        this.regForm.realname=''
       
        this.regForm.comment=''
        this.regFormVisible=true
      },
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ''
        } else {
          this.pwdType = 'password'
        }
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
           
            
            this.loading = true;
            this.$store.dispatch('Login', this.loginForm).then(() => {
              this.loading = false;
              setCookie("username",this.loginForm.username,15);
              setCookie("password",this.loginForm.password,15);
              this.$router.push({path: '/'})
            }).catch(() => {
              this.loading = false
            })
          } else {
            console.log('参数验证不合法！');
            return false
          }
        })
      },
      check(){
          //console.log(this.regForm.username)
          if (this.regForm.username.trim()==='') return
            
          checkUsername({"username":this.regForm.username}).then(response=>{
                  if (response.data.exist===1){

                    this.$message({
                          type: 'error',
                          message: '用户名已存在，请重新输入',
                          duration:1000
                      });
                      //this.$refs.usernameRef.focus()
                      this.regForm.username=''
                  }
                  
                }).catch((error) => {
                      console.log(error)
              
          });
      },
      handleRegister(){
       //添加注册功能
       this.$refs.regFormRef.validate(valid => {
          if (valid) {
               if (this.regForm.password!=this.regForm.password2){
                    this.$message({
                          type: 'error',
                          message: '两次密码输入不相同，请重新输入',
                          duration:1000
                      });
                    this.regForm.password2=''
                    return
               }

               let params={};
               
               params['username']=this.regForm.username
               params['password']=this.regForm.password
               params['telphone']=this.regForm.telphone
             
               params['realname']=this.regForm.realname
               params['roleid']=this.regForm.roleid
               params['comment']=this.regForm.comment


               register(params).then(response=>{
                    if (response.code===200) {
                        this.$message({
                              type: 'success',
                              message: '注册成功',
                              duration:1000
                          });
                      //this.$refs.usernameRef.focus()
                        this.regFormVisible=false
                    }
                 
                  
                }).catch((error) => {
                      console.log(error)
              
               });

           
          }
        })

      },
      
    }
  }
</script>

<style scoped>
  .login-form-layout {
    position: absolute;
    left: 0;
    right: 0;
    width: 360px;
    margin: 140px auto;
    border-top: 10px solid #409EFF;
  }

  .login-title {
    text-align: center;
  }

  .login-center-layout {
    background: #409EFF;
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    margin-top: 200px;
  }
</style>
